
if __name__ == '__main__':
    # 全局变量
    global_var = "I am global"


    def outer_function():
        # 闭包作用域变量
        enclosing_var = "I am enclosing"

        def inner_function():
            # 局部变量
            local_var = "I am local"
            print(local_var)  # 输出局部变量
            print(enclosing_var)  # 输出闭包作用域变量
            print(global_var)  # 输出全局变量

        inner_function()


    outer_function()
    # print(local_var)  # 这行会报错，因为local_var是局部变量，无法在函数外部访问

    def outer_function(x):
        # 外部函数的变量x是自由变量
        def inner_function(y):
            # 内部函数可以访问外部函数的变量x
            return x + y

        # 返回内部函数
        return inner_function


    # 创建闭包
    closure = outer_function(10)

    # 调用闭包，x=10, y=5
    result = closure(5)
    print(result)  # 输出15

    print("==============")

    def outer_function(x):
        def inner_function(y):
            return x + y

        return inner_function


    closure = outer_function(10)
    print(closure.__closure__)  # 输出(<cell at 0x...: int object at 0x...>,)
    print(closure.__closure__[0].cell_contents)  # 输出10